﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace myCollection
{
    public partial class Record : Form
    {
        private int id = 0;
        private int place;

        public Record(int id0 = 0)
        {
            InitializeComponent();
            this.id = id0;
            SQLite sqlite = new SQLite();
            sqlite.Connect();
            DataTable dt_mediatype = new DataTable();
            dt_mediatype = sqlite.GetDictionary(Dictionary.TypeD.MediaType, "");
            cbMediaType.DataSource = dt_mediatype;
            DataTable dt_datatype = new DataTable();
            dt_datatype = sqlite.GetDictionary(Dictionary.TypeD.DataType, "");
            cbDataType.DataSource = dt_datatype;
            DataTable dt_category = new DataTable();
            dt_category = sqlite.GetDictionary(Dictionary.TypeD.Category, "");
            cbCategory.DataSource = dt_category;
            DataTable dt_place = new DataTable();
            dt_place = sqlite.GetDictionary(Dictionary.TypeD.Place, "");
            cbPlace.DataSource = dt_place;
            if (this.id != 0)
            {
                DataTable dt = new DataTable();
                dt = sqlite.GetRecord(this.id);
                tbName.Text = dt.Rows[0]["name"].ToString();
                tbInfo.Text = dt.Rows[0]["info"].ToString();
                cbCategory.SelectedValue = dt.Rows[0]["category_id"];
                cbDataType.SelectedValue = dt.Rows[0]["datatype_id"];
                cbMediaType.SelectedValue = dt.Rows[0]["mediatype_id"];
                cbPlace.SelectedValue = dt.Rows[0]["place_id"];
                this.place = int.Parse(dt.Rows[0]["place_id"].ToString());
                this.lvRefresh();
                this.refreshHistory();
                this.enableForm(false);
            }
            sqlite.Disconnect();
        }

        private void refreshHistory()
        {
            tbHistory.Clear();
            SQLite sqlite = new SQLite();
            sqlite.Connect();
            DataTable dt = new DataTable();
            dt = sqlite.GetRecordHisory(this.id);
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                tbHistory.Text += dt.Rows[i]["date"].ToString() + ": " + dt.Rows[i]["text"].ToString() + "\r\n";
            }
            sqlite.Disconnect();
        }

        private void enableForm(bool b)
        {
            tbName.ReadOnly = !b;
            cbMediaType.Enabled = b;
            cbDataType.Enabled = b;
            cbCategory.Enabled = b;
            cbPlace.Enabled = b;
            tbInfo.ReadOnly = !b;
            btSave.Enabled = b;
            btEdit.Enabled = !b;
            btAddFile.Enabled = !b;
            btDelFile.Enabled = !b;
            btSaveFile.Enabled = !b;
            btViewFile.Enabled = !b;
        }

        private void btEdit_Click(object sender, EventArgs e)
        {
            this.enableForm(true);
        }

        private void btSave_Click(object sender, EventArgs e)
        {
            if (tbName.Text.Length == 0)
            {
                MessageBox.Show("Name is empty!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                tbName.Focus();
                return;
            }
            SQLite sqlite = new SQLite();
            sqlite.Connect();
            if (this.id == 0)
            {
                if (sqlite.ExistRecord(tbName.Text))
                {
                    MessageBox.Show("Name: " + tbName.Text + " is exist!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                if (sqlite.AddRecord(tbName.Text, int.Parse(cbMediaType.SelectedValue.ToString()), int.Parse(cbDataType.SelectedValue.ToString()), int.Parse(cbCategory.SelectedValue.ToString()), int.Parse(cbPlace.SelectedValue.ToString()), tbInfo.Text))
                {
                    MessageBox.Show("Add successfull!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.enableForm(false);
                    this.id = sqlite.LastInsertId();
                    this.place = int.Parse(cbPlace.SelectedValue.ToString());
                    sqlite.AddHistory("Add record", this.id);
                    this.refreshHistory();
                }
                else
                {
                    MessageBox.Show("Add fail!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                if (sqlite.ExistRecordUpdate(tbName.Text))
                {
                    MessageBox.Show("Name: " + tbName.Text + " is exist!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                if (sqlite.UpdateRecord(tbName.Text, int.Parse(cbMediaType.SelectedValue.ToString()), int.Parse(cbDataType.SelectedValue.ToString()), int.Parse(cbCategory.SelectedValue.ToString()), int.Parse(cbPlace.SelectedValue.ToString()), tbInfo.Text, this.id))
                {
                    if (this.place != int.Parse(cbPlace.SelectedValue.ToString()))
                    {
                        sqlite.AddHistory("Update place from: " + sqlite.GetDictionary(Dictionary.TypeD.Place, this.place).Rows[0]["name"].ToString() + " to: " + sqlite.GetDictionary(Dictionary.TypeD.Place, int.Parse(cbPlace.SelectedValue.ToString())).Rows[0]["name"].ToString(), this.id);
                        this.place = int.Parse(cbPlace.SelectedValue.ToString());
                    }
                    MessageBox.Show("Update successfull!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.refreshHistory();
                    this.enableForm(false);
                }
                else
                {
                    MessageBox.Show("Update fail!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            sqlite.Disconnect();
        }

        private void Record_Load(object sender, EventArgs e)
        {

        }

        private void btSaveFile_Click(object sender, EventArgs e)
        {
            if (listView1.Items.Count == 0)
            {
                MessageBox.Show("This record don't have files!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (listView1.SelectedItems.Count > 0)
            {
                saveFileDialog1.FileName = listView1.SelectedItems[0].SubItems[1].Text;
                if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    File.Copy(Properties.Settings.Default.dirfiles + "\\" + listView1.SelectedItems[0].SubItems[1].Text, saveFileDialog1.FileName);
                    MessageBox.Show("File save!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            else
            {
                MessageBox.Show("You must select file!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void viewFile()
        {
            if (listView1.Items.Count == 0)
            {
                MessageBox.Show("This record don't have files!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (listView1.SelectedItems.Count > 0)
            {
                if (this.ifPic(listView1.SelectedItems[0].SubItems[1].Text))
                {
                    int ii = 0, selectIndex = 0;
                    for (int i = 0; i < listView1.Items.Count; i++)
                    {
                        if (ifPic(listView1.Items[i].SubItems[1].Text))
                        {
                            ii++;
                        }
                    }
                    string[] files = new string[ii];
                    ii = 0;
                    for (int i = 0; i < listView1.Items.Count; i++)
                    {
                        if (ifPic(listView1.Items[i].SubItems[1].Text))
                        {
                            files[ii] = listView1.Items[i].SubItems[1].Text;
                            if (listView1.Items[i].SubItems[1].Text == listView1.SelectedItems[0].SubItems[1].Text)
                            {
                                selectIndex = ii;
                            }
                            ii++;
                        }
                    }
                    new PicView(files, selectIndex).Show();
                }
                else
                {
                    System.Diagnostics.Process.Start(Properties.Settings.Default.dirfiles + "\\" + listView1.SelectedItems[0].SubItems[1].Text);
                }
            }
            else
            {
                MessageBox.Show("You must select file!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void btViewFile_Click(object sender, EventArgs e)
        {
            this.viewFile();
        }

        private bool ifPic(string filename)
        {
            bool b = false;
            string ext = Path.GetExtension(filename).ToLower();
            if (ext == ".jpg" || ext == ".bmp" || ext == ".png" || ext == ".gif")
            {
                b = true;
            }
            return b;
        }

        private void lvRefresh()
        {
            listView1.Items.Clear();
            SQLite sqlite = new SQLite();
            sqlite.Connect();
            DataTable dt = new DataTable();
            dt = sqlite.GetRecordFiles(this.id);
            string[] row = new string[2];
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                row[0] = dt.Rows[i]["file"].ToString();
                row[1] = Utils.BytesToString(new FileInfo(Properties.Settings.Default.dirfiles + "\\" + dt.Rows[i]["file"].ToString()).Length);
                listView1.Items.Add((i + 1).ToString()).SubItems.AddRange(row);
            }
            sqlite.Disconnect();
        }

        private void btDelFile_Click(object sender, EventArgs e)
        {
            if (listView1.Items.Count == 0)
            {
                MessageBox.Show("This record don't have files!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if (listView1.SelectedItems.Count > 0)
            {
                if (MessageBox.Show("Delete file: " + listView1.SelectedItems[0].SubItems[1].Text + " ?", "Question", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.OK)
                {
                    SQLite sqlite = new SQLite();
                    sqlite.Connect();
                    sqlite.DeleteFile(listView1.SelectedItems[0].SubItems[1].Text);
                    sqlite.Disconnect();
                    File.Delete(Properties.Settings.Default.dirfiles + "\\" + listView1.SelectedItems[0].SubItems[1].Text);
                    this.lvRefresh();
                }
            }
            else
            {
                MessageBox.Show("You must select file!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void btAddFile_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string fileDest = "";
                if (Path.GetFileName(openFileDialog1.FileName).Length > 117)
                {
                    fileDest = Utils.TimeStamp().ToString() + "_" + Path.GetFileName(openFileDialog1.FileName).Replace(" ", "_").Substring(0, 113) + Path.GetExtension(openFileDialog1.FileName);
                }
                else
                {
                    fileDest = Utils.TimeStamp().ToString() + "_" + Path.GetFileName(openFileDialog1.FileName).Replace(" ", "_");
                }
                File.Copy(openFileDialog1.FileName, Properties.Settings.Default.dirfiles + "\\" + fileDest);
                SQLite sqlite = new SQLite();
                sqlite.Connect();
                sqlite.AddFile(fileDest, this.id);
                sqlite.Disconnect();
                this.lvRefresh();
            }
        }

        private void listView1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.viewFile();
        }
    }
}
